﻿using System;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Actya.Web.Infrastructure.ElFinderConnector.Utils
{
    public class ImageUtils
    {
    	private const string ThumbnailMode = "thumbnail";
    	private const string CropMode = "crop";

    	public static void Resize(string fromPath, string toPath, int width, int height, ImageFormat destFormat, string mode, int x, int y)
        {
            if (string.IsNullOrEmpty(fromPath))
                throw new NullReferenceException("parameter Image cannot be null or empty");

            if (!File.Exists(fromPath))
                throw new FileNotFoundException("Image does not exist at " + fromPath);

            Bitmap bitmap = new Bitmap(fromPath);

            String extension = Path.GetExtension(fromPath).ToLower();
            ImageFormat format;

            if (destFormat == null)
            {
                switch (extension.ToLower())
                {
                    case ".bmp":
                        format = ImageFormat.Bmp;
                        break;
                    case ".gif":
                        format = ImageFormat.Gif;
                        break;
                    case ".jpg":
                        format = ImageFormat.Jpeg;
                        break;
                    case ".jpeg":
                        format = ImageFormat.Jpeg;
                        break;
                    default:
                        format = ImageFormat.Png;
                        break;
                }
            }
            else
            {
                format = destFormat;
            }
            try
            {
                if (bitmap.Width <= width && bitmap.Height <= height && mode == ThumbnailMode)
                {
                    bitmap.Save(toPath, format);
                    bitmap.Dispose();
                    return;
                }
            }
            catch (Exception)
            {
                bitmap.Dispose();
            	throw;
            }

			Bitmap finalBitmap = null;

            try
            {
                Bitmap cropped = bitmap;
				if (mode == ThumbnailMode)
				{
					var cropSize = bitmap.Width;

					if (cropSize > bitmap.Height)
						cropSize = bitmap.Height;
					cropped = bitmap.Clone(new Rectangle(0, 0, cropSize, cropSize), bitmap.PixelFormat);
				}
				else if (mode == CropMode)
				{
					cropped = bitmap.Clone(new Rectangle(x, y, width, height), bitmap.PixelFormat);
				}

				int BitmapNewWidth;
                decimal Ratio;
                int BitmapNewHeight;

                Ratio = (decimal)cropped.Width / cropped.Height;
                BitmapNewWidth = width;

                decimal temp = width / Ratio;
                BitmapNewHeight = (int)temp;
                

                finalBitmap = new Bitmap(BitmapNewWidth, BitmapNewHeight);
                Graphics graphics = Graphics.FromImage(finalBitmap);
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.FillRectangle(Brushes.White, 0, 0, BitmapNewWidth, BitmapNewHeight);
                graphics.DrawImage(cropped, 0, 0, BitmapNewWidth, BitmapNewHeight);

                finalBitmap.Save(toPath, format);

            }
            finally
            {
                if (finalBitmap != null) 
					finalBitmap.Dispose();
                bitmap.Dispose();
            }

        }

        public static void Watermark(string sourceFile, string watermarkFile, int padding)
        {
            System.Drawing.Image sourceImage;
            var file = new System.IO.FileInfo(sourceFile);

            try
            {
                sourceImage = System.Drawing.Bitmap.FromFile(sourceFile);
            }
            catch
            {
                // This is not a valid image. Do nothing.
                return;
            }

            if (sourceImage.Width < 120 && sourceImage.Height < 120)
            {
                return;
            }

            var mark = new Bitmap(watermarkFile);

            var graphics = Graphics.FromImage(sourceImage);

            var rect = new Rectangle(sourceImage.Width - mark.Width - padding,
                 sourceImage.Height - mark.Height - padding,
                 mark.Width, mark.Height);

            graphics.DrawImage(mark, rect);


            String extension = Path.GetExtension(sourceFile).ToLower();
            ImageFormat format;
            switch (extension.ToLower())
            {
                case ".bmp":
                    format = ImageFormat.Bmp;
                    break;
                case ".gif":
                    format = ImageFormat.Gif;
                    break;
                case ".jpg":
                    format = ImageFormat.Jpeg;
                    break;
                case ".jpeg":
                    format = ImageFormat.Jpeg;
                    break;
                default:
                    format = ImageFormat.Png;
                    break;
            }

            sourceImage.Save(sourceFile + ".tmp", format);
            sourceImage.Dispose();
            graphics.Dispose();
            File.Delete(sourceFile);
            File.Move(sourceFile + ".tmp", sourceFile);
        }
    }
}
